import { defineStore } from "pinia";
import { getCompetitionList, getCompetitionDetail } from "@/api";

export const useCompetitionStore = defineStore("competition", {
  state: () => ({
    competitionList: [],
    currentCompetition: null,
    loading: false,
    totalCount: 0,
  }),

  getters: {
    getCompetitionById: (state) => (id) => {
      return state.competitionList.find((item) => item.id === id) || null;
    },
  },

  actions: {
    async fetchCompetitionList(params) {
      this.loading = true;
      try {
        const result = await getCompetitionList(params);
        this.competitionList = result.list || [];
        this.totalCount = result.total || 0;
      } catch (error) {
        console.error("获取竞赛列表失败", error);
      } finally {
        this.loading = false;
      }
    },

    async fetchCompetitionDetail(id) {
      this.loading = true;
      try {
        const result = await getCompetitionDetail(id);
        this.currentCompetition = result;
        return result;
      } catch (error) {
        console.error("获取竞赛详情失败", error);
        return null;
      } finally {
        this.loading = false;
      }
    },

    clearCurrentCompetition() {
      this.currentCompetition = null;
    },
  },
});
